# encoding: utf-8
from exts import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash


# cms用户
class CMSUser(db.Model):
    __tablename__ = "cms_users"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(20), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(40), nullable=False, unique=True)
    created_time = db.Column(db.DateTime, default=datetime.now)

    # 改写init方法
    def __init__(self, username, password, email):
        self.username = username
        self.password = generate_password_hash(password)
        self.email = email

    # 验证密码是否正确
    def check_password(self, password):
        return check_password_hash(self.password, password)

    def updatePassword(self, password):
        self.password = generate_password_hash(password)

    # 获取权限
    @property
    def permissions(self):
        if not self.roles:
            return 0
        all_permissions = 0
        for role in self.roles:
            permissions = role.permissions
            all_permissions |= permissions
        return all_permissions

    # 判断是否有权限
    def has_permission(self, permission):
        result = self.permissions & permission == permission
        return result

    # 判断是否是开发者
    @property
    def is_developer(self):
        result = self.has_permission(CMSPermission.ALL_PERMISSION)
        return result

# 权限——用户关联表
cms_role_user = db.Table(
    "cms_role_user",
    db.Column("cms_role_id", db.Integer, db.ForeignKey("cms_roles.id"), primary_key=True),
    db.Column("cms_user_id", db.Integer, db.ForeignKey("cms_users.id"), primary_key=True)
)

# 权限
class CMSPermission(object):
    # 所有权限
    ALL_PERMISSION = 0b11111111
    # 访问者权限
    VISITOR        = 0b00000001
    # 管理帖子权限
    POSTER         = 0b00000010
    # 管理评论权限
    COMMENTER      = 0b00000100
    # 管理板块权限
    BOARDER        = 0b00001000
    # 管理前台用户
    FRONTUSER      = 0b00010000
    # 管理后台权限
    CMSUSER        = 0b00100000
    # 管理后台用户
    ADMINDER       = 0b01000000

# 角色
class CMSRole(db.Model):
    __tablename__ = "cms_roles"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=True)
    desc = db.Column(db.String(50), nullable=False)
    created_time = db.Column(db.DateTime, default=datetime.now)
    permissions = db.Column(db.Integer, default=CMSPermission.VISITOR)

    users = db.relationship("CMSUser", secondary=cms_role_user, backref="roles")

